// Basic Particle System for Fireworks
// Based on common canvas animation tutorials

// 修复：使用DOMContentLoaded确保元素存在后再初始化
document.addEventListener("DOMContentLoaded", () => {
  console.log("Fireworks script initialized");

  const fireworksCanvas = document.getElementById("fireworks-canvas");
  if (!fireworksCanvas) {
    console.error("找不到烟花画布元素!");
    return;
  }

  const fireworksCtx = fireworksCanvas.getContext("2d");
  let particles = [];
  let rockets = [];
  let animationFrameId = null; // To control the animation loop

  const ROCKET_LIFESPAN = 100; // Frames before rocket explodes
  const PARTICLE_LIFESPAN = 60; // Frames particle is visible
  const GRAVITY = 0.05;
  const ROCKET_CHANCE = 0.04; // Chance of firing a new rocket each frame

  function clearFireworks() {
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
      animationFrameId = null;
    }
    fireworksCtx.clearRect(0, 0, fireworksCanvas.width, fireworksCanvas.height);
    particles = [];
    rockets = [];
  }

  class Particle {
    constructor(x, y, vx, vy, color, size, lifespan) {
      this.x = x;
      this.y = y;
      this.vx = vx;
      this.vy = vy;
      this.color = color;
      this.size = size;
      this.lifespan = lifespan;
      this.initialLifespan = lifespan; // To calculate alpha fade
    }

    update() {
      this.x += this.vx;
      this.y += this.vy;
      this.vy += GRAVITY; // Apply gravity
      this.lifespan--;
    }

    draw() {
      fireworksCtx.globalAlpha = Math.max(
        0,
        this.lifespan / this.initialLifespan
      ); // Fade out
      fireworksCtx.fillStyle = this.color;
      fireworksCtx.beginPath();
      fireworksCtx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      fireworksCtx.fill();
      fireworksCtx.globalAlpha = 1.0; // Reset alpha
    }
  }

  class Rocket extends Particle {
    constructor(x, y) {
      const targetX = x + (Math.random() - 0.5) * 50; // Slight horizontal variation
      const targetY = fireworksCanvas.height * (0.2 + Math.random() * 0.3); // Explode in upper part
      const angle = Math.atan2(targetY - y, targetX - x);
      const speed = 5 + Math.random() * 3;
      const vx = Math.cos(angle) * speed;
      const vy = Math.sin(angle) * speed;
      const color = `hsl(${Math.random() * 360}, 100%, 70%)`; // Bright color
      super(x, y, vx, vy, color, 2, ROCKET_LIFESPAN); // Rockets are small points
    }

    update() {
      super.update();
      // Rockets are less affected by gravity initially (or not at all)
      // this.vy -= GRAVITY * 0.5; // Counteract gravity slightly if desired

      // Explode when lifespan runs out
      if (this.lifespan <= 0) {
        this.explode();
      }
    }

    explode() {
      const particleCount = 50 + Math.floor(Math.random() * 50); // 50-100 particles
      const baseColorHue = parseFloat(this.color.match(/hsl\((\d+)/)[1]); // Get hue from rocket color

      for (let i = 0; i < particleCount; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 5 + 1; // Explosion speed
        const vx = Math.cos(angle) * speed;
        const vy = Math.sin(angle) * speed;
        const colorVariation = (Math.random() - 0.5) * 30; // Vary hue slightly
        const color = `hsl(${
          (baseColorHue + colorVariation + 360) % 360
        }, 100%, ${50 + Math.random() * 30}%)`; // Vary lightness
        const size = Math.random() * 2 + 1; // Particle size
        const lifespan = PARTICLE_LIFESPAN + Math.random() * 20;
        particles.push(
          new Particle(this.x, this.y, vx, vy, color, size, lifespan)
        );
      }
    }
  }

  function drawFireworks() {
    // 修复：使用半透明黑色背景
    fireworksCtx.fillStyle = "rgba(0, 0, 0, 0.1)";
    fireworksCtx.fillRect(0, 0, fireworksCanvas.width, fireworksCanvas.height);

    // Launch new rockets occasionally
    if (rockets.length < 5 && Math.random() < ROCKET_CHANCE) {
      // Limit concurrent rockets
      rockets.push(
        new Rocket(fireworksCanvas.width / 2, fireworksCanvas.height)
      ); // Launch from bottom center
    }

    // Update and draw rockets
    for (let i = rockets.length - 1; i >= 0; i--) {
      rockets[i].update();
      rockets[i].draw();
      if (rockets[i].lifespan <= 0) {
        rockets.splice(i, 1); // Remove exploded rocket
      }
    }

    // Update and draw particles
    for (let i = particles.length - 1; i >= 0; i--) {
      particles[i].update();
      particles[i].draw();
      if (particles[i].lifespan <= 0) {
        particles.splice(i, 1); // Remove dead particle
      }
    }

    // Keep animating if there are active elements
    if (rockets.length > 0 || particles.length > 0) {
      animationFrameId = requestAnimationFrame(drawFireworks);
    } else {
      // Animation finished, maybe clear completely after a delay
      setTimeout(() => {
        if (rockets.length === 0 && particles.length === 0) {
          // Check again in case new one started
          fireworksCtx.clearRect(
            0,
            0,
            fireworksCanvas.width,
            fireworksCanvas.height
          );
        }
      }, 1000); // Clear after 1 second of inactivity
      animationFrameId = null;
    }
  }

  function startFireworks() {
    console.log("Starting fireworks...");
    clearFireworks(); // Clear any previous state

    // 修复：确保canvas尺寸正确设置
    const canvasRect = fireworksCanvas.getBoundingClientRect();
    if (fireworksCanvas.width !== canvasRect.width) {
      fireworksCanvas.width = canvasRect.width;
    }
    if (fireworksCanvas.height !== canvasRect.height) {
      fireworksCanvas.height = canvasRect.height;
    }

    console.log(
      `Canvas dimensions: ${fireworksCanvas.width}x${fireworksCanvas.height}`
    );

    // 确保canvas尺寸不为0
    if (fireworksCanvas.width === 0) fireworksCanvas.width = 200;
    if (fireworksCanvas.height === 0) fireworksCanvas.height = 300;

    // 立即启动一个烟花，以便立即看到效果
    rockets.push(new Rocket(fireworksCanvas.width / 2, fireworksCanvas.height));

    // 延迟启动更多烟花
    for (let i = 0; i < 5; i++) {
      setTimeout(() => {
        rockets.push(
          new Rocket(
            fireworksCanvas.width * Math.random(),
            fireworksCanvas.height
          )
        );
      }, i * 300); // Stagger initial launches
    }

    // 启动动画循环
    if (!animationFrameId) {
      console.log("Starting animation loop");
      animationFrameId = requestAnimationFrame(drawFireworks);
    }
  }

  // 将函数暴露到全局作用域
  window.startFireworks = startFireworks;
  window.clearFireworks = clearFireworks;

  // 立即设置初始canvas尺寸
  if (fireworksCanvas.width === 0) fireworksCanvas.width = 200;
  if (fireworksCanvas.height === 0) fireworksCanvas.height = 300;
});
